<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>损溢管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
	<script charset="utf-8" src="${pageContext.request.contextPath}/lib/layui-xtree/layui-xtree.js"></script>
</head>
<body class="layui-anim layui-anim-up">
    <div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>损溢管理</cite>
        </a>
      </span>
    </div>
    <div class="x-body">
      <div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="keyword" name="keyword" lay-filter="orderNumber">
								<option value="">请选择损溢类型</option>
								<option>亏损</option>
								<option>正常</option>
								<option>盈余</option>
							</select>
						</div>
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon">&#xe615;</i>检索</button>
	  </div>
      <xblock>
			<button id="add" class="layui-btn layui-btn-warm"><i class="layui-icon"></i>新增损溢单</button>
			<button id="dels" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
			<!-- <button class="layui-btn layui-btn-blue" onclick="doExportall()"><i class="layui-icon layui-icon-up"></i>导出</button> -->
			<!-- <button class="layui-btn layui-btn-blue" onclick="uploadExcel()"><i class="layui-icon layui-icon-down"></i>导入</button> -->
      </xblock> 
	  <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	</div>
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
	</script>

	<!-- 导入框 -->
	<div id="importDiv" hidden="hidden">
		<form class="layui-form" id="uploadform">
			<div style="margin: 20px 0 20px 140px;">
				<input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
			</div>
		</form>
		<button class="layui-btn layui-btn-blue" lay-filter="uplodeform" style="margin-left: 80px">导入数据</button>&emsp;&emsp;&emsp;&emsp;
		<button type="button" class="layui-btn" id="downloadFile">下载模板</button>
	</div>
	
	
	<!-- 新增表单 -->
	
	 <div id="addDivID" hidden>
							<form class="layui-form" id="addFormID">
								<xblock>
									<table>
										<tr>
											<td><label class="layui-form-label">盘点单号</label></td>
											<td>
												<div style="width: 184px; float: left;">
													<select id="inventory_order" name="inventory_order" lay-verify="inventory_order" lay-filter="inventory_order" style="width: 184px">
														<option value="-1">请选择盘点单号</option>
														<c:forEach items="${allInventory }" var="inventory">
														<option value="${inventory.inventory_order_num}">${inventory.inventory_order_num }</option>
														</c:forEach>
													</select>
												</div>
												<div style="margin-top: 12px;">
			                                        <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
			                                    </div>
											</td>
											<td><label class="layui-form-label">物料名称</label></td>
											<td>
												<div style="width: 190px; float: left;">
													<select id="materialName" name="materialName" lay-verify="materialName" lay-filter="materialName">
														<option value="-1">请先选择物料名称</option>
													</select>
												</div>
												<div style="margin-top: 12px;">
			                                        <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
			                                    </div>
											</td>
										</tr>
                        				<tr style="height: 10px"></tr>
										<tr>
											<td><label class="layui-form-label">物料编号</label></td>
											<td>
								
												<input class="layui-input" id="materialNumber" name="materialNumber" style="width: 184px;display:inline" >
												
												<div class="layui-inline" style="margin-top: 10px;">
	                                                <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
	                                            </div>
											</td>
											<td><label class="layui-form-label">损溢类型</label></td>
											<td>
												<input class="layui-input" id="loss_spillover_type" name="loss_spillover_type" style="width: 184px;display:inline" >
												<div class="layui-inline" style="margin-top: 10px;">
	                                                <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
	                                            </div>
												<!-- <div style="width: 190px; float: left;">
													<select id="loss_spillover_type" lay-verify="loss_spillover_type" name="loss_spillover_type" lay-filter="loss_spillover_type">
														<option value="0">请选择损溢类型</option>
														<option>盈亏</option>
														<option>盈余</option>
													</select>
												</div>
												<div style="margin-top: 12px;">
			                                        <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
			                                    </div> -->
											</td>
										</tr>
										<tr style="height: 10px"></tr>
										<tr>
											<td><label class="layui-form-label">差异数量</label></td>
											<td>
												
													<input class="layui-input" id="inventory_different" name="inventory_different" style="width: 184px;display:inline">
												
												<div class="layui-inline" style="margin-top: 10px;">
	                                                <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
	                                            </div>
											</td>
											<td><label class="layui-form-label">差异原因</label></td>
											<td>
												<input class="layui-input" id="different_remark" name="different_remark" style="width:190px">
											</td>
										</tr>
										<tr>
											<td><label class="layui-form-label">审&nbsp;批&nbsp;人</label></td>
											<td>
												<div id="xtree1" style="width:200px; height: 200px; border:1px solid #DBDBDB; margin-top: 10px; overflow: auto;"></div>
											</td>
											<td><label class="layui-form-label">抄&nbsp;送&nbsp;人</label></td>
											<td>
												<div id="xtree2" style="width:200px; height: 200px; border:1px solid #DBDBDB; margin-top: 10px; overflow: auto;"></div>
											</td>
											<td colspan="2">
												<input class="layui-hide" lay-verify="approval_id"  lay-filter="approval_id" id="approval_id" name="approval_id" style="width: 206px">
											</td>
											<td colspan="2">
											<input class="layui-hide" lay-verify="copy_id" lay-filter="copy_id" id="copy_id" name="copy_id" style="width: 206px">
											</td>
										</tr>
									</table>
								</xblock>
								<xblock>
									<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:260px; margin-top:10px; margin-bottom: 10px">提交</button>
									&emsp;&emsp;&emsp;&emsp;<button type="reset" class="layui-btn layui-btn-primary" style="margin-top:10px; margin-bottom: 10px">重置</button>
								</xblock>
					</form>
      </div>
	

	

	<script type="text/javascript">
		
		var approvalName = "";
		var copyName = "";
		
		
        var table;
		layui.use(['table','layer','upload','form','laydate'], function(){
			table = layui.table;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;
			var $ = layui.jquery, active = {
				reload:function () {
					var keyword01 = $("#keyword").val();
					table.reload('contenttable',{
						method:'get',
						where:{"keyword01":keyword01}
					});
				}
			}
			$('.layui-btn').on('click', function(){
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			});
			table.render({
				elem: '#tableList'
				,url:'${pageContext.request.contextPath }/lossSpillover/queryLossSpilloverCriteria.do'
				,toolbar: '#toolbar'
				,title: '损溢管理'
				,id :'contenttable'
				,limits:[10,20,30]
                ,defaultToolbar:['filter', 'print']
				,cols: [[
				  {type: 'checkbox', fixed: 'left', },
				  {field:'', title:'序号', width: 50, /* sort: true,  */type:'numbers', align:'center'},
				  {field:'inventory_order', title:'盘点单', align:'center'},
				  {field:'loss_spillover_order', title:'损益单单号', align:'center'},
				  {field:'loss_spillover_type', title:'损溢类型', align:'center'},
				  {field:'materialName', title:'物料名称', align:'center'},
				  {field:'materialNumber', title:'物料编号', align:'center'},
				  /* {field:'inventory_before', title:'盘点前', align:'center', edit: true},
				  {field:'inventory_after', title:'盘点后', align:'center', edit: true}, */
				  {field:'inventory_different', title:'差异数量', align:'center'},
				  {field:'different_remark', title:'差异备注', align:'center', edit: true},
				  {field:'approval_name', title:'审批人名称', align:'center'},
				  {field:'approval_static', title:'审批结果', align:'center'
					  ,templet: function(d){
					        if(d.approval_status == "0"){
					        	//$('#sh').attr('class','layui-btn layui-btn-danger layui-btn-xs');
					        	return "未审批";
					        }else if(d.approval_status == "1"){
					        	//$('#bsh').attr('class','layui-btn layui-btn-primary layui-btn-xs layui-disabled');
					        	return "审批通过";
					        }else{
					        	//$('#bsh').attr('class','layui-btn layui-btn-primary layui-btn-xs layui-disabled');
					       		return "审批驳回";
					        }
					      }  
				  },
				  {field:'copy_name', title:'抄送人名称', align:'center'},
				  {field:'createrName', title:'创建人', align:'center'},
				  {field:'creater_date', title:'创建时间', align:'center'},
				  //{fixed:'right', unresize: true, title:'操作', toolbar: '#rowToolbar', align:'center',width: 100}
				]]
				,page: true
                ,done : function(){
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                        
                    })
                }
			});

			//监听行工具事件
			table.on('tool(tableList)', function(obj){
				var data = obj.data;
				//alert(data.id)
				var idArr = new Array();
				//单个删除
				if(obj.event === 'del'){
				  layer.confirm('确定删除吗？', function(index){
					var id = obj.data.id;
					idArr[0] = id;
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/lossSpillover/deleteLossSpilloverById.do',
						data:{ "idArr" : idArr },
						success:function(data){
							if(data > 0){
								toastrStyle();
								toastr.success("删除成功！");
								setTimeout(function(){
									location.reload();
								},1000);
								/*setTimeout(function(){
									//关闭模态框
									//父页面刷新
									window.location.reload();
								},2000);*/
							}else{
								toastrStyle();
								toastr.warning("删除失败！");
								setTimeout(function(){
									location.reload();
								},1000);
							}
						}
					});
					layer.close(index);
				  });
				}
			});
			
			/**
			 *	选择盘点单后的操作
			 */
			form.on('select(inventory_order)', function(data){
				if(data.value =="-1"){
					$("#materialName").empty();
					$("#materialName").append("<option value='-1'>请先选择盘点单</option>");
					$("#inventory_different").val("");
					$("#materialNumber").val(""); 
				}else{
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/inventory/queryInventoryDetailByOrder.do',
						data:{ "orderId" : data.value },
						dataType:'JSON',
						async:false,
						success:function(data){
							$("#materialName").empty(); 
							$("#materialName").append("<option value='-1'>请选择物料名称</option>");
							for(var i = 0 ;i<data.length;i++){
								$("#materialName").append("<option value='"+data[i].id+"'>"+data[i].materiel_name+"</option>");
							} 
						}
					});
				}
				form.render();
				
			});	
			
			/**
			 *	选择物料后的操作
			 */
			form.on('select(materialName)', function(data){
				if(data.value =="-1"){
					$("#inventory_different").val("");
					$("#materialNumber").val(""); 
				}else{
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/inventory/queryInventoryDetailById.do',
						data:{ "id" : data.value },
						dataType:'JSON',
						async:false,
						success:function(data){
							var json = data.data;
							console.log(json);
							 //$("#inventory_different").val("123");
							for (var i = 0; i < json.length; i++) {
								 $("#inventory_different").val(json[i].difference_quantity);
								 var number = $("#inventory_different").val();
								 if(number > 0){
									 $('#loss_spillover_type').val('盈余');
								 }else if(number < 0){
									 $('#loss_spillover_type').val('亏损');
								 }else{
									 $('#loss_spillover_type').val('正常');
								 }
								 $("#materialNumber").val(json[i].materiel_num); 
							}
							
						}
					});
					
				}
				form.render();
			});

			/**
			 * 通用表单提交(AJAX方式)(新增)
			 */
			form.on('submit(addForm)', function (data) {
				$.ajax({
					url : '${pageContext.request.contextPath}/lossSpillover/addLossSpillover.do',
					data: $("#addFormID").serialize(),
					cache : false,
					type : "post",
					}).done(
						function(res) {
							if (res > 0) {
								toastrStyle();
								toastr.success('添加成功！');
								setTimeout(function(){
									location.reload();
								},1000);
							}
						}
					).fail(
						function(res) {
							toastrStyle();
							toastr.error('添加失败！');
							setTimeout(function(){
								location.reload();
							},1000);
						}
					)
					return false;
			});

			/**
			 * 新增表单校验
			 */
			form.verify({
				//value：表单的值item：表单的DOM对象
				reactionPlan: function(value, item){
					if(value == ''){
						return '反应计划字段不能为空';
					}
				},
				copy_id: function(value, item){
					if(value == ''){
						return '请选择至少一个抄送人';
					}
				},
				inventory_order: function(value, item){
					if(value == '-1'){
						return '请选择物料单';
					}
				},
				approval_id: function(value, item){
					if(value == ''){
						return '请选择至少一个审批人';
					}
				},
				materialName: function(value, item){
					if(value == '-1'){
						return '物料名称字段不能为空';
					}
				},
				loss_spillover_type: function(value, item){
					if(value == '0'){
						return '请选择损溢类型';
					}
				}
				
				
			});

			laydate.render({
                elem: '#creater_date'
            });
			
			//增加
            $("#add").click(function(){
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['680px', '500px'] 	//宽  高
                    ,title: '新增'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,success: function(){
                    	var xtree1 = new layuiXtree({
             		       elem: 'xtree1'               //必填
             		       , form: form                 //必填
             		       , data: '${pageContext.request.contextPath}/dept/getDeptXtree.do'
             		       , isopen: false  			//加载完毕后的展开状态，默认值：true
             		       , ckall: true    			//启用全选功能，默认值：false
             		       , ckallback: function () {
             		    	  var xtreeArr = new Array();
            		    	   xtreeArr = xtree1.GetChecked();
            		       		apapprovalName = "";
            		    	
            		    	  for (var i = 0; i < xtreeArr.length; i++) {
            		    		 apapprovalName=xtreeArr[i].value;
								}
            	
            		           console.log(apapprovalName); 			//开关value值，也可以通过data.elem.value得到
            		           $("#approval_id").val(apapprovalName);
             		    	   
             		       } //全选框状态改变后执行的回调函数
             		       , icon: {        			//三种图标样式，更改几个都可以，用的是layui的图标
             		           open: "&#xe625;"       	//节点打开的图标
             		           , close: "&#xe623;"    	//节点关闭的图标
             		           , end: "&#xe623;"      	//末尾节点的图标
             		       }
             		       , color: {       			//三种图标颜色，独立配色，更改几个都可以
             		           open: "#EE9A00"        	//节点图标打开的颜色
             		           , close: "#EEC591"     	//节点图标关闭的颜色
             		           , end: "#828282"       	//末级节点图标的颜色
             		       }
             		       , click: function (data) {  				//节点选中状态改变事件监听，全选框有自己的监听事件
             		    	  var xtreeArr = new Array();
             		    	   xtreeArr = xtree1.GetChecked();
             		       		apapprovalName = "";
             		    	
             		    	  for (var i = 0; i < xtreeArr.length; i++) {
             		    		 apapprovalName=xtreeArr[i].value;
								}
             	
             		           console.log(apapprovalName); 			//开关value值，也可以通过data.elem.value得到
             		           $("#approval_id").val(apapprovalName);
             		           //console.log(data.othis); 			//得到美化后的DOM对象
             		       }
             			});
                    	
                    	
                    	var xtree2 = new layuiXtree({
              		       elem: 'xtree2'               //必填
              		       , form: form                 //必填
              		       , data: '${pageContext.request.contextPath}/dept/getDeptXtree.do'
              		       , isopen: false  			//加载完毕后的展开状态，默认值：true
              		       , ckall: true    			//启用全选功能，默认值：false
              		       , ckallback: function () {
              		    	 var xtreeArr = new Array();
            		    	   xtreeArr = xtree2.GetChecked();
            		       		copyName = "";
            		    	
            		    	  for (var i = 0; i < xtreeArr.length; i++) {
            		    		    copyName+=xtreeArr[i].value+",";
								}
            		    	  copyName=copyName.slice(0,copyName.length-1)
            					console.log("copy"+copyName); 			//开关value值，也可以通过data.elem.value得到
            		           $("#copy_id").val(copyName);
              		    	   
              		       } //全选框状态改变后执行的回调函数
              		       , icon: {        			//三种图标样式，更改几个都可以，用的是layui的图标
              		           open: "&#xe625;"       	//节点打开的图标
              		           , close: "&#xe623;"    	//节点关闭的图标
              		           , end: "&#xe623;"      	//末尾节点的图标
              		       }
              		       , color: {       			//三种图标颜色，独立配色，更改几个都可以
              		           open: "#EE9A00"        	//节点图标打开的颜色
              		           , close: "#EEC591"     	//节点图标关闭的颜色
              		           , end: "#828282"       	//末级节点图标的颜色
              		       }
              		       , click: function (data) {  //节点选中状态改变事件监听，全选框有自己的监听事件
              		    	 var xtreeArr = new Array();
              		    	   xtreeArr = xtree2.GetChecked();
              		       		copyName = "";
              		    	
              		    	  for (var i = 0; i < xtreeArr.length; i++) {
              		    		    copyName+=xtreeArr[i].value+",";
								}
              		    	copyName=copyName.slice(0,copyName.length-1)
              					console.log("copy"+copyName); 			//开关value值，也可以通过data.elem.value得到
              		           $("#copy_id").val(copyName);
              		           //console.log(data.othis); 			//得到美化后的DOM对象
              		       }
              			});
                     	
                    	
                        laydate.render({
                            elem: '#creater_date'
                        });
                        form.render();
                    }
                });
			});

			//批量删除
			$("#dels").click(function(){
				var rowData = table.checkStatus('contenttable');
				var data = rowData.data;
				var idArr = new Array();
				if(data.length == 0){
					toastrStyle();
					toastr.warning("请至少选择一条记录！");
				}
				for(var i=0;i < data.length;i++){
					idArr[i] = data[i].id;
				}
				$.ajax({
					type:'post',
					url:'${pageContext.request.contextPath }/lossSpillover/deleteLossSpilloverById.do',
					data:{"idArr" : idArr},
					success:function(data){
						layer.confirm('确定删除吗？', function(index){
							if(data > 0){
								toastrStyle();
								toastr.success("删除成功！");
								setTimeout(function(){
									location.reload();
								},1000);
								setTimeout(function(){
									//使用setTimeout（）方法设定定时2000毫秒
									//关闭模态框
									//父页面刷新
									window.location.reload();
								},2000);
							}else{
								toastrStyle();
								toastr.warning("删除失败！");
								location.reload();
							}
						});
					}
				});
			});

			//"损溢单"的行内编辑事件
			table.on('edit(tableList)', function(obj){ 
				var fieldValue = obj.value, 	//得到修改后的值 
				rowData = obj.data, 			//得到所在行所有键值 
				fieldName = obj.field; 			//得到字段
				layui.use('jquery',function(){ 
					var $=layui.$; 
					$.ajax({ 
						type: "post", 
						url: "${pageContext.request.contextPath }/lossSpillover/updateLossSpilloverById.do", 
						data: { id:rowData.id, fieldName:fieldName, fieldValue:fieldValue }, 
						success: function(data){ 
							layer.msg('修改成功'); 
						} 
					}); 
				});
			});
		});
	</script>
</body>
</html>
